package znyl.nursing.controller;

import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import znyl.common.annotation.Log;
import znyl.common.core.controller.BaseController;
import znyl.common.core.domain.AjaxResult;
import znyl.common.enums.BusinessType;
import znyl.common.utils.PDFUtil;
import znyl.common.utils.file.FileUtils;
import znyl.nursing.domain.HealthAssessment;
import znyl.nursing.dto.HealthAssessmentDto;
import znyl.nursing.service.IHealthAssessmentService;
import znyl.common.utils.poi.ExcelUtil;
import znyl.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import znyl.oss.client.OSSAliyunFileStorageService;

/**
 * 健康评估Controller
 * 
 * @author 睢高浩
 * @date 2025-11-07
 */
@Api(tags =  "健康评估相关接口")
@RestController
@RequestMapping("/nursing/healthAssessment")
public class HealthAssessmentController extends BaseController
{
    @Autowired
    private IHealthAssessmentService healthAssessmentService;
    @Resource
    private OSSAliyunFileStorageService fileStorageService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询健康评估列表
     */
    @ApiOperation(value = "查询健康评估列表")
    @PreAuthorize("@ss.hasPermi('nursing:assessment:list')")
    @GetMapping("/list")
    public TableDataInfo list(HealthAssessment healthAssessment)
    {
        startPage();
        List<HealthAssessment> list = healthAssessmentService.selectHealthAssessmentList(healthAssessment);
        return getDataTable(list);
    }

    /**
     * 导出健康评估列表
     */
    @ApiOperation(value = "导出健康评估列表")
    @PreAuthorize("@ss.hasPermi('nursing:assessment:export')")
    @Log(title = "健康评估", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HealthAssessment healthAssessment)
    {
        List<HealthAssessment> list = healthAssessmentService.selectHealthAssessmentList(healthAssessment);
        ExcelUtil<HealthAssessment> util = new ExcelUtil<HealthAssessment>(HealthAssessment.class);
        util.exportExcel(response, list, "健康评估数据");
    }

    /**
     * 获取健康评估详细信息
     */
    @ApiOperation(value = "获取健康评估详细信息")
    @PreAuthorize("@ss.hasPermi('nursing:assessment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@ApiParam(value = "健康评估ID", required = true)
                                  @PathVariable("id") Long id)
    {
        return success(healthAssessmentService.selectHealthAssessmentById(id));
    }

    /**
     * 新增健康评估
     */
    @PreAuthorize("@ss.hasPermi('nursing:assessment:add')")
    @Log(title = "健康评估", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增健康评估")
    public AjaxResult add(@ApiParam(value = "健康评估实体", required = true)
                              @RequestBody HealthAssessmentDto healthAssessment)
    {
        Long id = healthAssessmentService.insertHealthAssessment(healthAssessment);
        return success(id);
    }

    /**
     * 修改健康评估
     */

    @PreAuthorize("@ss.hasPermi('nursing:assessment:edit')")
    @Log(title = "健康评估", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改健康评估")
    public AjaxResult edit(@ApiParam(value = "健康评估实体", required = true)  @RequestBody HealthAssessment healthAssessment) {
        {
            return toAjax(healthAssessmentService.updateHealthAssessment(healthAssessment));
        }

    }
    /**
     * 删除健康评估
     */
    @ApiOperation(value = "删除健康评估")
    @PreAuthorize("@ss.hasPermi('nursing:assessment:remove')")
    @Log(title = "健康评估", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(healthAssessmentService.deleteHealthAssessmentByIds(ids));
    }
    /**
     * 上传体检报告
     * */
    @ApiOperation(value = "上传体检报告")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file,String idCardNo) throws Exception
    {
        // 添加非空校验
        if (idCardNo == null || idCardNo.trim().isEmpty()) {
            return AjaxResult.error("身份证号不能为空");
        }
        try
        {
            // 获得原始文件名
            String originalFilename = file.getOriginalFilename();
            // 获得文件扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extension;
            String url = fileStorageService.store(fileName, file.getInputStream());
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", url); //注意：这里的值要改为url，前端访问的地址
            ajax.put("newFileName", FileUtils.getName(fileName));// 这个没啥用，也可删除
            ajax.put("originalFilename", originalFilename);
            //读取PDF文件
            String text = PDFUtil.pdfToString(file.getInputStream());
            System.out.println(text);
            //将输出的病理报告存放到Redis中以身份证号为key
            redisTemplate.opsForHash().put("healthReport",idCardNo,text);
            ajax.put("text", text);
            System.out.println("上传成功"+ajax);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
